<template>
    <nut-popup v-model:visible="visible" position="bottom">
        <nut-picker 
            :columns="pickerColumns" 
            :title="computedTitle"
            @confirm="onConfirm"
            @cancel="onCancel"
        ></nut-picker>
    </nut-popup>
</template>

<script lang="ts" setup>
import { computed } from 'vue';

interface CascaderOption {
    key: string;
    title: string;
    text: string;
    value: string;
}

const props = defineProps({
    // 标题前缀，如 "当前科室"、"当前医院"、"当前部门" 等
    titlePrefix: {
        type: String,
        default: '当前选择'
    },
    // 当前选中的值，用于显示在标题中
    currentValue: {
        type: String,
        default: ''
    },
    // 是否显示空值时的占位符
    showEmptyPlaceholder: {
        type: Boolean,
        default: true
    },
    // 是否在选择后立即关闭弹窗
    closeOnSelect: {
        type: Boolean,
        default: true
    }
});

const visible = defineModel<boolean>('visible');
const options = defineModel<Array<CascaderOption>>('options');

const emits = defineEmits(["change"]);

// 将options转换为picker格式
const pickerColumns = computed(() => {
    return [options.value?.map(item => ({
        text: item.text,
        value: item.value
    })) || []];
});

// 计算标题
const computedTitle = computed(() => {
    const prefix = props.titlePrefix;
    const current = props.currentValue || '';
    return `${prefix}:${current}`;
});

// 确认选择事件
const onConfirm = (selectedOptions: any) => {
    // 根据实际的数据结构获取选中的值
    let selectedItem = null;
    
    if (selectedOptions.selectedValue && selectedOptions.selectedValue.length > 0) {
        selectedItem = selectedOptions.selectedValue[0];
    } else if (selectedOptions.selectedOptions && selectedOptions.selectedOptions.length > 0) {
        selectedItem = selectedOptions.selectedOptions[0];
    }
    
    if (selectedItem) {
        // 直接使用选中的项目数据
        emits("change", [selectedItem]);
    }
    
    visible.value = false;
};

// 取消选择事件
const onCancel = () => {
    visible.value = false;
};
</script>
